<script setup>
import { ref, watch, onMounted } from 'vue';
import hospitalapi from '../api'
import { ElMessageBox,ElMessage } from "element-plus";

//绑定数据
const tableData=ref([]);
//控制新增信息窗口是否显示
const addWinVisible=ref(false);
//控制上传窗口是否显示
const upWinVisible = ref(false);

//控制编辑信息窗口是否显示
const editWinVisible=ref(false);
//新增数据绑定对象（双向绑定)
const addObject=ref({});
//编辑数据绑定对象（双向绑定）
const editObject=ref({})
 // 存储所有床位数据
const beds = ref([]);

const admitWinVisible = ref(false);  // 入院窗口
const admitObject = ref({  });          // 入院对象

const upObject=ref({});  //文件上传部分
const updatilWinVisible=ref(false);
const selectedRows= ref({});




//查询数据文本
const checkObj=ref({
  page:1,
  size:5
});
const total=ref(90);

var admitIndex=-1
//记录修改数据的下标
var editIndex=-1
//挂载页面时查询数据
onMounted( function () {
 checkData();
  
});
const checkData=async function(val){
  //相当于点了分页按钮
  if(typeof val=='number'){
    checkObj.value.page=val
  }
  //查询数据
  let result=await hospitalapi.get("/api/patient",checkObj.value)

  //更新表格中的数据
  tableData.value=result.data.list;
  total.value=result.data.count;
  
}




const doctors = ref([]);

const wards=ref([]);

const departments=ref([]);


async function admitt(index,row){
  openAdmitWin(); // 进入入院信息窗口
  
  admitObject.value.pid = row.id;
   admitObject.value.name = row.name;


   const result = await hospitalapi.get("/api/department");
  departments.value=result.data.list;
  console.log(departments.value);

  
    const responsea = await hospitalapi.get("/api/ward");
   wards.value=responsea.data.list;
   console.log(wards.value);

}

const depchange =async (newVal) => {
  // newVal 是选中的值
  console.log('选中的科室:', newVal);

  admitObject.value.did = null;

    //发送请求获取
  const response = await hospitalapi.get(`/api/doctorbydep_id?dep_id=${newVal}`);
 
      // 更新 
      doctors.value = response.data;
    
 
  };





const wnamechange =async (newVal) => {
  // newVal 是选中的值
  console.log('选中的病房名:', newVal);

  admitObject.value.bid = null;
  try{
    //发送请求获取wid有关的bednember
  const response = await hospitalapi.get(`/api/bednumberbywid?wid=${newVal}`);
  if (response.data && response.data.length > 0) {
      // 更新 beds 数组为新的床位数据
      beds.value = response.data;
    } else {
      // 如果没有床位数据，可以提示用户或进行其他操作
      ElMessage.info('当前选中的病房没有可用的床位');
      admitObject.value.bid = null;
    }
  } catch (error) {
    console.error('获取床位信息失败:', error);
    ElMessage.error('获取床位信息失败，请稍后重试');
  }
 
   


};
    





// 打开入院窗口
const openAdmitWin = () => {
  admitObject.value = {
    admissiondate: new Date().toISOString().substring(0, 10), // 设置为今天
    

  };
  admitWinVisible.value = true; // 打开入院窗口
};









const admitSave = async () => {
 
  try {
    // 发送入院数据到后端API
    console.log(admitObject.value)
     
    const response  =  hospitalapi.postJson("/api/addcases", admitObject.value)
.then(response => {
     
console.log(response);
     if (response.code ==200) {
      // 使用 Element Plus 的消息提示组件
      ElMessage.success("入院信息保存成功！");
      
      // 关闭入院窗口
      admitWinVisible.value = false;
      
      // 这里可以添加其他成功处理的逻辑，比如刷新数据列表等
    } else {
      // 如果响应码不是200，使用 Element Plus 的消息提示组件显示错误信息
      ElMessage.error("保存失败，请重试。");
    }
    })
  } catch (error) {
    console.error("保存入院信息失败:", error);
    // 使用 Element Plus 的消息提示组件显示错误信息
    ElMessage.error("保存失败，请重试。");
  }
};






const del=function(index,row){
  ElMessageBox.confirm(
    "确认要删除该行数据吗",
    "提示",{
      confirmButtonText:"确认",
      concelButtonText:"取消",
      type:"warning"
    }
  ).then(async function(){
      //提交数据
      let result=await hospitalapi.del("/api/patient",row.id);
      if(result.code=200){
        //刷新表格数据
        tableData.value.splice(index,1);
        //提示删除成功
        ElMessage({
          type:'success',
          message:'删除成功',
        })
      }else{
        ElMessage({
          type:'info',
          message:result.message
        })
      }

  }) 
   
    
}
//新增数据 addObject 
const addSave=async function(){
  console.log("Sending data:", addObject.value);
  //发送请求
  let result=await hospitalapi.postJson("/api/patient",addObject.value);
  tableData.value.unshift(result.data);
    //表格数据变更
  ElMessage({
    type:'success',
    message:'保存成功',
  });
//提示
  closeaddWin();
}

//保存编辑数据
const editSave=async function(index){
  //发送请求
  let result=await hospitalapi.putJson("/api/patient",editObject.value);
  //刷新表格
  tableData.value[editIndex]=result.data;
  //提示
  ElMessage({
    type:'success',
    message:'保存成功',
  });
  editWinVisible.value=false;
}

//点击编辑按钮执行的方法
const edit=function(index,row){
  //记录修改数据的下标
  editIndex=index;
  //绑定要修改的数据
  editObject.value.id=row.id;
  editObject.value.name=row.name;
  editObject.value.sex=row.sex;
  editObject.value.age=row.age;
  editObject.value.contact=row.contact;

  //打开对话框
  editWinVisible.value=true;
}



//显示窗口
const openaddWin=()=>{
  addObject.value={};
  addWinVisible.value=true;
}
const closeaddWin=()=>{
  addWinVisible.value=false;
}



//显示上传窗口
const openUpWin = () => {
    upWinVisible.value = true;
  }
  //关闭上传窗口
  const closeUpWin = async () => {
    upWinVisible.value = false;
  }
  //文件上传成功后，打开详情界面
  const upSuccess = function (result, uploadFile) {
    //console.log(result.data);
    upObject.value = result.data;
    //console.log(upObject.value)
    updatilWinVisible.value = true;
  }

  // 处理选中项变化  
  function handleSelectionChange(val) {
    selectedRows.value = val;
    //console.log(selectedRows.value);
  }

  const updatilSave = function () {
    if (selectedRows.value.length === 0) {
      ElMessage({
        type: 'info',
        message: '没有选中任何项',
      });
      return;
    }

    (async function () {
      // 假设 selectedRows.value 是一个包含多个对象的数组，每个对象代表一行数据  
      const addPromises = selectedRows.value.map(row => {
        // 发送 POST 请求，将整行数据作为 JSON 发送  
        return hospitalapi.postJson("/api/patient", row); // 直接发送 row 对象  
      });

      try {
        // 等待所有请求完成  
        const results = await Promise.allSettled(addPromises);
        console.log('All requests have been processed:', results);

        // 处理请求结果（如果需要的话）  
        // 例如，可以遍历 results 来查找失败的请求  
        const failedRequests = results.filter(result => result.status === 'rejected');
        if (failedRequests.length > 0) {
          console.error('Some requests failed:', failedRequests);
          alert('部分导入失败，请检查！');
        } else {
          // 假设 idsToadd 是你用来追踪哪些 ID 已经被添加的数组  
          // 从本地数据中移除已导入的项  
          console.log(upObject.value);
          upObject.value = upObject.value.filter(row => !selectedRows.value.some(s => s.id === row.id));
          console.log("====");
          console.log(selectedRows.value)
          console.log(upObject.value);
          // 提示成功  
          ElMessage({
            type: 'success',
            message: '导入成功',
          });
          checkData();
        }
      } catch (error) {
        // 这里的 catch 主要用于捕获 Promise.allSettled 之外的错误（理论上不应该发生）  
        console.error('导入过程中发生未预期的错误：', error);
        alert('导入失败，请稍后再试！');
      }
    })();
  };


</script>


<template>
<el-input v-model="checkObj.name" style="width: 150px" placeholder="查询的病人名字" />
<el-input v-model="checkObj.contact" style="width: 150px" placeholder="查询的病人的电话" />
<el-button type="success" @click="checkData">查询</el-button>
<el-button type="success" @click="addWinVisible=true">新增</el-button>
<el-button type="success" @click="upWinVisible=true">上传Excel</el-button>
<el-table
  :data="tableData"
  style="width: 100%"
 >

    <el-table-column prop="name" label="名字" width="380" />
    <el-table-column prop="sex" label="性别" width="380" />
    <el-table-column prop="contact" label="联系电话"  width="380"/>

<el-table-column label="操作"  width="200" label-class-name="center">  
    <template #default="scope">
      <div style="display: flex; justify-content: center; align-items: center;">
     <el-button type="danger" @click="del(scope.$index,scope.row)">删除</el-button>
     <el-button type="warning" @click="edit(scope.$index,scope.row)">编辑</el-button>
     <el-button type="primary" @click="admitt(scope.$index, scope.row)">入院</el-button>
      </div>
    </template>
   </el-table-column>  
</el-table>

  <!-- current-page分页组件初始现实的页码  size：每业的条数 -->
  <el-pagination
  :page-size="checkObj.size"
  :current-page="checkObj.page"
   background layout="prev, pager, next" :total="total" @current-change="checkData"/>



    <!-- start 新增信息的弹出框 -->
  <el-dialog v-model="addWinVisible" title="新增" width="500">
     <el-form :model="addObject">
      
      
      <el-form-item label="姓名" label-width="80">
        <el-input v-model="addObject.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" label-width="80">
  <el-select v-model="addObject.sex" placeholder="请选择">
    <el-option label="男" value="男"></el-option>
    <el-option label="女" value="女"></el-option>
  </el-select>
</el-form-item>
      <el-form-item label="年龄" label-width="80">
        <el-input v-model="addObject.age" autocomplete="off" />
      </el-form-item>
      <el-form-item label="联系电话" label-width="80">
        <el-input v-model="addObject.contact" autocomplete="off" maxlength="11"/>
      </el-form-item>
    

      
    

    </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="addWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addSave" >
          保存
        </el-button>
      </div>
          </template>
  </el-dialog>
<!-- end 新增信息的弹出框 -->

<!-- start 编辑信息的弹出框 -->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
     <el-form :model="editObject">
      <el-form-item label="姓名" label-width="80">
        <el-input v-model="editObject.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" label-width="80">
  <el-select v-model="editObject.sex" placeholder="请选择">
    <el-option label="男" value="男"></el-option>
    <el-option label="女" value="女"></el-option>
  </el-select>
</el-form-item>
      <el-form-item label="年龄" label-width="80">
        <el-input v-model="editObject.age" autocomplete="off" />
      </el-form-item>
      <el-form-item label="联系电话" label-width="80">
        <el-input v-model="editObject.contact" autocomplete="off" maxlength="11"/>
    </el-form-item>
    </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="editWinVisible = false">取消</el-button>
        <el-button type="primary" @click="editSave" >
          保存
        </el-button>
      </div>
          </template>
  </el-dialog>
<!-- end 编辑信息的弹出框 -->

<!-- start 入院信息弹出框 -->

<el-dialog v-model="admitWinVisible" title="新增" width="500">
    <el-form :model="admitObject"> <!-- 使用 admitObject 代替 addObject -->
      <el-form-item label="患者名字" label-width="80">
  <el-input v-model="admitObject.name" readonly /> <!-- 设置为只读 -->
        </el-form-item>

        <el-form-item label="科室" label-width="80">
        <el-select v-model="admitObject.dep_id"  placeholder="请选择科室" @change="depchange" >
          <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id" ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="主治医生" label-width="80">
        <el-select v-model="admitObject.did"  placeholder="请选择医生" >
          <el-option v-for="doctor in doctors" :key="doctor.id" :label="doctor.name" :value="doctor.id" ></el-option>
        </el-select>
      </el-form-item>
      

      <el-form-item label="病房名" label-width="80">
        <el-select v-model="admitObject.wname" placeholder="请选择病房" @change="wnamechange">
          <el-option v-for="ward in wards" :key="ward.id" :label="ward.name" :value="ward.id" />
          
        </el-select>
      </el-form-item>

      <el-form-item label="床位号" label-width="80">
        <el-select v-model="admitObject.bid" value-key="id" placeholder="请选择床位" >
          <el-option v-for="bed in beds" :key="bed.id" :label="bed.bednember" :value="bed.id" />
          
        </el-select>
      </el-form-item>


      


    
      <el-form-item label="病例描述" label-width="80">
        <el-input v-model="admitObject.desc" autocomplete="off" />
      </el-form-item>

      <el-form-item label="入院日期" label-width="80">
        <el-input v-model="admitObject.admissiondate" readonly />
      </el-form-item>

      
      <el-form-item label="病人状态" label-width="80">
        <el-select v-model="admitObject.status" placeholder="请选择">
          <el-option label="住院" value="住院"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="admitWinVisible = false">取消</el-button>
        <el-button type="primary" @click="admitSave">保存</el-button> <!-- 改为调用 admitSave -->
      </div>
    </template>
</el-dialog>
<!-- end 入院信息弹出框 -->


 <!-- start上传信息的弹出框 -->
  <el-dialog v-model="upWinVisible" title="上传" width="500">
    <el-upload class="upload-demo" drag action="/api/patientexcel" :on-success="upSuccess" multiple>
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          jpg/png files with a size less than 500kb
        </div>
      </template>
    </el-upload>
  </el-dialog>
  <!-- end上传信息的弹出框 -->

   <!-- start上传信息详情的弹出框 -->
  <el-dialog v-model="updatilWinVisible" title="新增" width="1000">
    <el-table :data="upObject" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="病人" width="120">
        <template #default="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column prop="id" label="id" width="150" />
      <el-table-column prop="name" label="名字" />
    <el-table-column prop="sex" label="性别" />
    <el-table-column prop="age" label="年龄" />
    <el-table-column prop="contact" label="手机号" />

    </el-table>
    <div class="dialog-footer">
      <el-button @click="updatilWinVisible = false">取消</el-button>
      <el-button type="primary" @click="updatilSave">导入</el-button>
    </div>
  </el-dialog>
  <!-- end上传信息详情的弹出框 -->



</template>

<style scoped>
.el-button {
  margin-right: 5px; /* 只保留必要的右边距 */
}

/* 表格操作列的样式 */
.el-table-column .el-table__body .center {
  display: flex;
  justify-content: space-between; /* 按钮和列的边缘保持一定间距 */
}

/* 调整表格列宽 */
.el-table-column:nth-child(3) { /* 假设联系电话是第三列 */
  min-width: 200px; /* 根据需要调整 */
}

/* 如果需要，可以为特定列设置更具体的选择器 */
.el-table .el-table-column--contact {
  width: 20%; /* 或使用 min-width */
}
</style>